package com.sxwl.common.utils;

import com.sxwl.common.pojo.UserInfo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.joda.time.DateTime;

import java.security.PrivateKey;
import java.security.PublicKey;

/**
 * @author reading
 * @Description TODO
 * @Date 2020/4/5 13:39
 */
public class JwtUtils {
    public static String generateToken(int id ,String userName,int expire,PrivateKey privateKey) throws Exception {
        return Jwts.builder()
                .claim("id", id)
                .claim("username", userName)
                .setExpiration(DateTime.now().plusMinutes(expire).toDate())
                .signWith(SignatureAlgorithm.RS256,privateKey)
                .compact();

    }

    /**
     * 获取token中的用户信息
     *
     * @param token     用户请求中的令牌
     * @param publicKey 公钥
     * @return 用户信息
     * @throws Exception
     */
    public static UserInfo getInfoFromToken(String token, PublicKey publicKey) throws Exception {
        Jws<Claims> claimsJws =  parserToken(token, publicKey);
        Claims body = claimsJws.getBody();
        Integer userId = (Integer)body.get("id");
        String username = (String)body.get("username");
        return UserInfo.builder().username(username).id(userId).build();

    }
    /**
     * 公钥解析token
     *
     * @param token     用户请求中的token
     * @param publicKey 公钥
     * @return
     * @throws Exception
     */
    private static Jws<Claims> parserToken(String token, PublicKey publicKey) {

        return Jwts.parser().setSigningKey(publicKey).parseClaimsJws(token);
    }
}
